﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Threading;
using System.Activities;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.Build.Workflow.Tracking;
using Microsoft.TeamFoundation.Build.Workflow;
using System.ComponentModel;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.Build.Workflow.Activities;

namespace TFSBuildActivitiesLibrary
{
    /// <summary>
    /// Code activity that adds new build to build queue.
    /// </summary>
    [BuildActivity(HostEnvironmentOption.All)]
    public sealed class QueueNewBuild : CodeActivity<IBuildDetail>
    {
        /// <summary>
        /// Sets the parent build detail object.
        /// </summary>
        /// <value>
        /// The build detail.
        /// </value>
        [RequiredArgument]
        public InArgument<IBuildDetail> BuildDetail { get; set; }
        /// <summary>
        /// Sets the build name for a child build.
        /// </summary>
        /// <value>
        /// The name of the build.
        /// </value>
        [RequiredArgument]
        public InArgument<string> BuildName { get; set; }
        /// <summary>
        /// Sets the child build quality.
        /// </summary>
        /// <value>
        /// The build quality.
        /// </value>
        [DefaultValue("Undefined")]
        public InArgument<string> BuildQuality { get; set; }
        /// <summary>
        /// Sets the child build input arguments.
        /// </summary>
        /// <value>
        /// The build input arguments.
        /// </value>
        public InArgument<IDictionary<string,object>> InputArguments { get; set; }

        /// <summary>
        /// When implemented in a derived class, performs the execution of the activity.
        /// </summary>
        /// <param name="context">The execution context under which the activity executes.</param>
        protected override IBuildDetail Execute(CodeActivityContext context)
        {
            IBuildDetail buildDetail = context.GetValue(this.BuildDetail);
            string buildDefinitionName = context.GetValue(this.BuildName);
            string strBuildQuality = context.GetValue(this.BuildQuality);
            IDictionary<string, object> dictInputArguments = context.GetValue(this.InputArguments);

            IQueuedBuild qbuild = Utilities.BeginExecute(context, buildDetail, buildDefinitionName, dictInputArguments);
            if (qbuild == null) return null;

            Utilities.EndExecute(context, qbuild, strBuildQuality);

            return qbuild.Build;
        }
    }
}
